import 'dart:typed_data';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:landlore/customWidget/iosStyleCalendar.dart';
import 'package:mccounting_text/mccounting_text.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';

import '../customWidget/reviewScreenNormalProgressIndicator.dart';
import '../customWidget/reviewScreenThirdRow.dart';
import '../customWidget/yearMonthCupPicker.dart';
import '../dbUtil/databaseHelper.dart';
import '../model/orderVO.dart';
import '../model/reviewVO.dart';
import 'dart:io';
import 'package:path/path.dart';

class ReviewScreen extends StatefulWidget {
  int currentYear;
  int currentMonth;

  ReviewScreen(this.currentYear, this.currentMonth, {super.key});

  @override
  State<ReviewScreen> createState() => _ReviewScreenState();
}

class _ReviewScreenState extends State<ReviewScreen> {
  //缓存区数据,确定后才使用
  late String selectedDateTemp;
  late int currentYearTemp = DateTime.now().year;
  late int currentMonthTemp = DateTime.now().month;

  var tableTitleStyle = TextStyle(fontSize: 20.sp, color: Colors.black);
  var tableTextStyle = TextStyle(fontSize: 20.sp, color: Colors.white);

  ReviewVO currentMonthData = ReviewVO.empty();
  List<ReviewVO> currentYearList = [];
  List<ReviewVO> lastYearList = [];
  double sum = 0;
  List<ReviewVO> tableData = [];
  DatabaseHelper dbHelper = DatabaseHelper.instance;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getReviewData();
  }

  _getReviewData() async {
    //获取 目标月 的数据
    ReviewVO _currentMonthData = await dbHelper.getReviewByYearAndMonth(
        widget.currentYear, widget.currentMonth);
    //获取 目标年 的数据
    List<ReviewVO> _currentYearList =
        await dbHelper.getReviewByYearFilled(widget.currentYear, false);
    //获取 目标年去年 的数据
    List<ReviewVO> _lastYearList =
        await dbHelper.getReviewByYearFilled(widget.currentYear - 1, false);
    //获取累计进账
    double _sum = await dbHelper.getReviewSumIncome();
    //获取 表格 的数据
    List<ReviewVO> _tableData = await dbHelper.getReviewTableData();

    setState(() {
      currentMonthData = _currentMonthData;
      currentYearList = _currentYearList;
      lastYearList = _lastYearList;
      sum = _sum;
      tableData = _tableData;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MediaQuery(
      data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
      child: Scaffold(
        appBar: AppBar(
          elevation: 0,
          backgroundColor: const Color(0xff7797f1),
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios,
              size: 35.sp,
              color: Colors.black,
            ),
            onPressed: () => Navigator.pop(context),
          ),
          // title:
        ),
        body: SingleChildScrollView(
          child: Container(
            color: const Color(0xffbde0fe),
            child: Column(
              children: [
                //=========================第一行=========================
                Container(
                  padding: EdgeInsets.only(
                      top: 15.h, bottom: 30.h, left: 20.w, right: 50.w),
                  decoration: BoxDecoration(
                    color: const Color(0xffe9c46a),
                    borderRadius: BorderRadius.only(
                        bottomLeft: Radius.circular(35.r),
                        bottomRight: Radius.circular(35.r)),
                    gradient: const LinearGradient(
                        colors: [Color(0xff7797f1), Color(0xff1d51e7)],
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '累计进账',
                            style: TextStyle(
                                fontSize: 40.sp,
                                color: Colors.white70,
                                fontWeight: FontWeight.w900),
                          ),
                          McCountingText(
                            begin: 0,
                            end: sum,
                            precision: 1,
                            style: TextStyle(
                                fontSize: 45.sp, color: Colors.black87),
                            duration: const Duration(milliseconds: 2300),
                            curve: Curves.fastOutSlowIn,
                          )
                        ],
                      ),
                      GestureDetector(
                          onTap: () {
                            showModalBottomSheet(
                                context: context,
                                builder: (context) {
                                  return SizedBox(
                                    height: 350.h,
                                    child: Column(
                                      children: [
                                        Expanded(
                                          child: YearMonthCupPicker(
                                            callback: (value, year, month) {
                                              selectedDateTemp = value;
                                              currentYearTemp = year;
                                              currentMonthTemp = month;
                                            },
                                            inputYear: widget.currentYear,
                                            inputMonth: widget.currentMonth,
                                          ),
                                        ),
                                        CupertinoButton(
                                            child: Text(
                                              "确定",
                                              style: TextStyle(
                                                  fontSize: 25.sp,
                                                  backgroundColor:
                                                      Colors.white),
                                            ),
                                            onPressed: () {
                                              setState(() {
                                                widget.currentYear =
                                                    currentYearTemp;
                                                widget.currentMonth =
                                                    currentMonthTemp;
                                                _getReviewData();
                                              });
                                              Navigator.pop(context);
                                            })
                                      ],
                                    ),
                                  );
                                });
                          },
                          child: IosStyleCalendar(
                              year: widget.currentYear,
                              month: widget.currentMonth)),
                    ],
                  ),
                ),
                //=========================第二行=========================
                Container(
                  margin:
                      EdgeInsets.symmetric(vertical: 15.h, horizontal: 15.w),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    // border: Border.all(color: Colors.grey, width: 1.w),
                    borderRadius: BorderRadius.all(Radius.circular(20.r)),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey.withOpacity(0.5),
                        spreadRadius: 5,
                        blurRadius: 7,
                        offset: const Offset(0, 3),
                      )
                    ],
                  ),
                  child: Row(
                    children: [
                      Expanded(
                          flex: 1,
                          child: Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Column(
                              children: [
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Icon(
                                      Icons.monetization_on_outlined,
                                      size: 40.sp,
                                      color: const Color(0xffDCB826),
                                    ),
                                    Text(
                                      '本月进账',
                                      style: TextStyle(fontSize: 25.sp),
                                    ),
                                  ],
                                ),
                                McCountingText(
                                  begin: 0,
                                  end: (currentMonthData.rent! +
                                      currentMonthData.otherCharge! +
                                      currentMonthData.eleCharge! +
                                      currentMonthData.waterCharge!),
                                  precision: 0,
                                  style: TextStyle(fontSize: 30.sp),
                                  duration: const Duration(milliseconds: 1500),
                                  curve: Curves.fastOutSlowIn,
                                )
                              ],
                            ),
                          )),
                      // 垂直分割线
                      Container(
                        width: 2.w,
                        height: 45.h,
                        color: Colors.grey[300],
                      ),
                      // VerticalDivider(color: Colors.green,thickness: 5.w,width: ,),
                      Expanded(
                          flex: 1,
                          child: Container(
                            padding: const EdgeInsets.all(8.0),
                            margin: EdgeInsets.only(right: 5.w),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Stack(alignment: Alignment.center, children: [
                                  SizedBox(
                                      width: 60.w,
                                      height: 60.w,
                                      child: CircularProgressIndicatorCustom(
                                        value: currentMonthData.fulRentRate!,
                                      )),
                                  Text(
                                    (currentMonthData.fulRentRate! * 100)
                                        .toStringAsFixed(0),
                                    style: TextStyle(
                                        fontSize: 30.sp,
                                        fontWeight: FontWeight.w800,
                                        color: Colors.black54),
                                  )
                                ]),
                                Container(
                                  padding: EdgeInsets.only(left: 8.0.w),
                                  child: Text(
                                    '满租率',
                                    style: TextStyle(fontSize: 23.sp),
                                  ),
                                )
                              ],
                            ),
                          ))
                    ],
                  ),
                ),

                //=========================第三部分,选项卡和线形图=========================
                ThirdRow(
                    currentMonthData: currentMonthData,
                    currentYearList: currentYearList,
                    lastYearList: lastYearList),
                //=========================第四部分,表格=========================
                Divider(
                  color: Colors.white38,
                  thickness: 5.h,
                  indent: 100.w,
                  endIndent: 100.w,
                ),
                Stack(children: [
                  Container(
                    margin: EdgeInsets.symmetric(vertical: 55.h),
                    color: const Color(0xff0e2336),
                    child: Table(
                      border: TableBorder.all(color: Colors.white30),
                      defaultVerticalAlignment:
                          TableCellVerticalAlignment.middle,
                      children: [
                        TableRow(
                            decoration:
                                const BoxDecoration(color: Colors.redAccent),
                            children: [
                              TableCell(
                                  child: Center(
                                      child: Padding(
                                padding: EdgeInsets.symmetric(vertical: 15.h),
                                child: Text('年份', style: tableTitleStyle),
                              ))),
                              TableCell(
                                  child: Center(
                                child: Text('总收', style: tableTitleStyle),
                              )),
                              TableCell(
                                  child: Center(
                                child: Text('满租率',
                                    style: tableTitleStyle.copyWith(
                                        fontSize: 18.sp)),
                              )),
                              TableCell(
                                  child: Center(
                                child: Text('租金', style: tableTitleStyle),
                              )),
                              TableCell(
                                  child: Center(
                                child: Text('附加费',
                                    style: tableTitleStyle.copyWith(
                                        fontSize: 18.sp)),
                              )),
                              TableCell(
                                  child: Center(
                                child: Text('电费', style: tableTitleStyle),
                              )),
                              TableCell(
                                  child: Center(
                                child: Text('水费', style: tableTitleStyle),
                              )),
                            ]),
                        ...List.generate(
                            tableData.length,
                            (index) => TableRow(children: [
                                  TableCell(
                                    child: Center(
                                        child: Text(
                                            '${tableData[index].createDateYear!}',
                                            style: tableTextStyle)),
                                  ),
                                  TableCell(
                                    child: Center(
                                        child: Text(
                                            (tableData[index].rent! +
                                                    tableData[index]
                                                        .otherCharge! +
                                                    tableData[index]
                                                        .eleCharge! +
                                                    tableData[index]
                                                        .waterCharge!)
                                                .toStringAsFixed(0),
                                            style: tableTextStyle)),
                                  ),
                                  TableCell(
                                    child: Center(
                                        child: Padding(
                                            padding: EdgeInsets.symmetric(
                                                vertical: 4.h),
                                            child: Stack(
                                                alignment: Alignment.center,
                                                children: [
                                                  CircularProgressIndicatorCustom(
                                                    value: tableData[index]
                                                        .fulRentRate!,
                                                  ),
                                                  Text(
                                                    (tableData[index]
                                                                .fulRentRate! *
                                                            100)
                                                        .toStringAsFixed(0),
                                                    style: TextStyle(
                                                        fontSize: 14.sp,
                                                        fontWeight:
                                                            FontWeight.w800,
                                                        color: Colors.white70),
                                                  )
                                                ]))),
                                  ),
                                  TableCell(
                                    child: Center(
                                        child: Text(
                                            tableData[index]
                                                .rent!
                                                .toStringAsFixed(0),
                                            style: tableTextStyle)),
                                  ),
                                  TableCell(
                                    child: Center(
                                        child: Text(
                                            tableData[index]
                                                .otherCharge!
                                                .toStringAsFixed(0),
                                            style: tableTextStyle)),
                                  ),
                                  TableCell(
                                    child: Center(
                                        child: Text(
                                            tableData[index]
                                                .eleCharge!
                                                .toStringAsFixed(0),
                                            style: tableTextStyle)),
                                  ),
                                  TableCell(
                                    child: Center(
                                        child: Text(
                                            tableData[index]
                                                .waterCharge!
                                                .toStringAsFixed(0),
                                            style: tableTextStyle)),
                                  ),
                                ]))
                      ],
                    ),
                  ),
                  Positioned(
                      top: 5.h,
                      left: 5.w,
                      child: Row(
                        children: [
                          Text(
                            '年度数据',
                            style: TextStyle(
                                fontSize: 50.sp,
                                color: Colors.white.withOpacity(0.9),
                                fontWeight: FontWeight.w900,
                                shadows: const [
                                  Shadow(
                                      color: Colors.black12,
                                      offset: Offset(-2, -4),
                                      blurRadius: 3)
                                ]),
                          ),
                        ],
                      ))
                ]),
                //=========================第五部分=========================
                ElevatedButton(
                    onPressed: () async {
                      String path =
                          join(await getDatabasesPath(), "landlord.db");

                      File file = File(path);

                      String? downloadDirectory =
                          await FilePicker.platform.getDirectoryPath();
                      print(downloadDirectory);
                      DateTime now = DateTime.now();
                      String formattedDateTime =
                          "${now.year}${now.month}${now.day}"
                          "${now.hour}${now.minute}${now.second}";

                      String backupDatabasePath =
                          '${downloadDirectory!}/backup_db_$formattedDateTime.db';
                      try {
                        Uint8List content = await file.readAsBytes();
                        File backupFile = File(backupDatabasePath);
                        await backupFile.writeAsBytes(content);

                        final snackBar = SnackBar(
                          content: Text(
                            '数据已经备份到:$backupDatabasePath',
                            style: TextStyle(fontSize: 20.sp),
                          ),
                        );
                        ScaffoldMessenger.of(context).showSnackBar(snackBar);
                        print('Database file copied to :$backupDatabasePath');
                      } catch (e) {
                        print(e);
                      }
                    },
                    child: const Text('输出备份')),
                ElevatedButton(
                    onPressed: () async {
                      FilePickerResult? result =
                          await FilePicker.platform.pickFiles(
                        type: FileType.any,
                        // allowedExtensions: ['db'], // 可根据数据库文件的扩展名进行调整
                      );

                      if (result != null && result.files.isNotEmpty) {
                        String newDatabasePath = result.files.single.path!;
                        if (!newDatabasePath.endsWith('db')) {
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(
                              content: Text('替换数据库时出错：文件格式不正确'),
                            ),
                          );
                          return;
                        }

                        // 在此处可以执行数据库备份操作（可选）

                        // 替换当前数据库文件
                        try {
                          final currentDatabasePath = join(
                              await getDatabasesPath(),
                              'landlord.db'); // 替换为当前数据库的路径
                          File newDatabaseFile = File(newDatabasePath);
                          File currentDatabaseFile = File(currentDatabasePath);
                          await currentDatabaseFile.delete();
                          await currentDatabaseFile.create();

                          await newDatabaseFile.copy(currentDatabasePath);
                          // await currentDatabaseFile.copy(newDatabasePath);

                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(
                              content: Text('数据库已成功替换！'),
                            ),
                          );
                        } catch (error) {
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(
                              content: Text('替换数据库时出错：$error'),
                            ),
                          );
                        }
                      }
                    },
                    child: const Text('选择备份文件并替换数据库')),
                ElevatedButton(
                    onPressed: () async {
                      //loading加载中动画
                      showDialog(
                        context: context,
                        barrierDismissible: false,
                        // Prevent dismissing the dialog by tapping outside
                        builder: (BuildContext context) {
                          return AlertDialog(
                            content: Row(
                              children: [
                                const CircularProgressIndicator(),
                                SizedBox(width: 16.w),
                                const Text('处理中...'),
                              ],
                            ),
                          );
                        },
                      );

                      List<OrderVO> dataList = await dbHelper.getOrder();
                      dataList.forEach((data) async {
                        String eleImage = data.eleImage ?? '';
                        String waterImage = data.waterImage ?? '';
                        if (eleImage.isNotEmpty) {
                          //检测图片文件是否存在,不存在则清除order记录中的图片地址
                          if (!(await File(eleImage).exists())) {
                            dbHelper.clearCacheImg(data.id!, 0);
                          }
                        }
                        if (waterImage.isNotEmpty) {
                          //检测图片文件是否存在,不存在则清除order记录中的图片地址
                          if (!(await File(eleImage).exists())) {
                            dbHelper.clearCacheImg(data.id!, 1);
                          }
                        }
                      });

                      Navigator.of(context).pop();

                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                          content: Text('已清除!'),
                        ),
                      );
                      // if (result != null && result.files.isNotEmpty) {
                    },
                    style: const ButtonStyle(
                        backgroundColor:
                            MaterialStatePropertyAll(Colors.green)),
                    child: const Text('清除失效图片')),
                SizedBox(height: 100.h,)
              ],
            ),
          ),
        ),
      ),
    );
  }
}
